package com.test.lifeCycle.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName JdkProxyBeanPostProcessor
 * @Description
 * @Author lihaiyang
 * @Date 2022/7/17 17:00
 * @Version 1.0
 */
@Slf4j(topic = "e")
public class JdkProxyBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("d")) {
			ClassLoader classLoader = this.getClass().getClassLoader();
			Class<?>[] interfaces = bean.getClass().getInterfaces();
			Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new MyInvocationHandler(bean));
			return proxy;
		}
		return bean;
	}

	class MyInvocationHandler implements InvocationHandler {
		Object object;

		public MyInvocationHandler(Object o) {
			this.object = o;
		}
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			log.debug("aop-before");
			Object invoke = method.invoke(object, args);
			log.debug("aop-after");
			return invoke;
		}
	}

}
